import Vue from 'vue'
import Vuex from 'vuex'
import axios from './axios.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    isLogin: true,
  },
  mutations: {
    saveLoginStatus(state, { token }) {
      sessionStorage.setItem('token', token)
    },
  },
  actions: {
    loginIn({ commit }, { username, password }) {
      //登录
      return new Promise(async (resolve, reject) => {
        const { meta, data } = await axios.post('/login', { username, password })
        if (meta.status == 200) {
          commit('saveLoginStatus', { token: data.token })
          resolve(meta)
        } else {
          reject(meta)
        }
      })
    },
    logout({ commit }, { token }) {
      return new Promise((resolve) => {
        commit('saveLoginStatus', token)
        sessionStorage.setItem('activePath','/home/users')
        resolve(true)
      })
    },
    getRequest({ commit }, { path, params }) {
      return new Promise(async (resolve, reject) => {
        const { meta, data } = await axios.get(path, { params: { ...params } })
        if (meta.status === 200 || meta.status === 201) {
          resolve(data)
          console.log(data)
        } else {
          reject(meta.msg)
        }
      })
    },
    putRequest({ commit }, { path, params }) {
      return new Promise(async (resolve, reject) => {
        const { meta, data } = await axios.put(path,params)
        if (meta.status === 200 || meta.status === 201) {
          resolve({data,meta})
          console.log(data,meta)
        } else {
          console.log(meta);
          reject(meta.msg)
        }
      })
    },
    postRequest({ commit }, { path, params }) {
      return new Promise(async (resolve, reject) => {
        const { meta, data } = await axios.post(path, params )
        if (meta.status === 200 || meta.status === 201) {
          resolve({meta,data})
          console.log(data,meta)
        } else {
          reject(meta.msg)
        }
      })
    },
    deleteRequest({commit},{path,params}){
      return new Promise(async (resolve,reject)=>{
          const {meta,data} =await axios.delete(path,params)
          if(meta.status===200||meta.status===201){
            resolve(meta)
            console.log(data,meta);
          }else{
            reject(meta.msg)
          }
      })
    }
  },
})

export default store
